package com.simulate;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.simulate.MockLocationThread.OnGPSSendListener;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.List;

/**
 * 主界面
 *
 * @author wangqiuwei
 * @since 2015/9/10
 */
public class HomeActivity extends Activity implements LocationListener, OnGPSSendListener, View.OnClickListener {

    private List<String> trackData = new ArrayList<String>();// 历史轨迹

    private String[] filelist = null;
    private String selectFileName = "";

    private static String mocLocationProvider = LocationManager.GPS_PROVIDER;

    private MockLocationThread mockLocationThread;
    private LocationManager locationManager;
    private MapView mMapView;
    private AMap aMap;

    private final static int DIALOG_FILE = 1;

    static boolean isSatellite = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if( !Utils.isMockSettingsON(this) ){
            Toast.makeText(this, "请先打开允许模拟位置选项", Toast.LENGTH_LONG).show();
            return;
        }

        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initMap();

        if (initTrackFileList()) {
            selectFileName = filelist[0];
            initTrackData(selectFileName);
        }

        initLocation();

        try {
            mockLocationThread = new MockLocationThread(locationManager, HomeActivity.this, LocationManager.GPS_PROVIDER, trackData);
            mockLocationThread.registerOnSendListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }

        findViewById(R.id.start_btn).setOnClickListener(this);
        findViewById(R.id.stop_btn).setOnClickListener(this);
        findViewById(R.id.last_btn).setOnClickListener(this);
        findViewById(R.id.next_btn).setOnClickListener(this);
        findViewById(R.id.mapMode_btn).setOnClickListener(this);

        // 设置指定的可视区域地图
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39.971036, 116.314659), 12.0f));
        aMap.getUiSettings().setZoomGesturesEnabled(true);

        setTitle("当前文件：" + selectFileName);
    }

    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
    }

    private void initLocation() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationManager.addTestProvider(mocLocationProvider, false, false, false, false, true, true, true, 0, 5);
        locationManager.setTestProviderEnabled(mocLocationProvider, true);
        locationManager.requestLocationUpdates(mocLocationProvider, 0, 0, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, Menu.FIRST + 1, 1, "轨迹文件列表");
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST + 1:
                showDialog(DIALOG_FILE);
                break;
        }
        return false;
    }

    @Override
    protected Dialog onCreateDialog(int id, Bundle args) {
        Dialog dialog = null;
        switch (id) {
            case DIALOG_FILE:
                Builder builder = new android.app.AlertDialog.Builder(this);

                // 设置对话框的标题
                builder.setTitle("请选择要测试的轨迹文件");
                // 0: 默认第一个单选按钮被选中
                builder.setSingleChoiceItems(filelist, 0, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        selectFileName = filelist[which];
                        initTrackData(selectFileName);
                    }

                });

                // 添加一个确定按钮
                builder.setPositiveButton(" 确 定 ", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        Button mStart = (Button) findViewById(R.id.start_btn);
                        mStart.performClick();
                    }
                });
                // 创建一个单选按钮对话框
                dialog = builder.create();
                break;
        }
        return dialog;

    }

    private boolean initTrackFileList() {
        File file = new File(Constants.TRACKFILE_FOLDER);
        if (file.isDirectory()) {
            filelist = file.list();
            if (filelist.length > 0) {
                return true;
            } else
                Toast.makeText(HomeActivity.this, Constants.TRACKFILE_FOLDER + "下面没有文件", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(HomeActivity.this, Constants.TRACKFILE_FOLDER + "不是一个路径", Toast.LENGTH_SHORT).show();
        }

        return false;
    }

    // 读SD卡里的历史记录
    // 文件约定格式：经度，纬度，速度，方向，与下一个轨迹的时间间隔
    private boolean initTrackData(String fileName) {
        File file = new File(Constants.TRACKFILE_FOLDER + "//" + fileName);
        BufferedReader reader = null;
        trackData.clear();
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null && tempString.length() > 0) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
                trackData.add(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            } else
                return false;
        }

        this.setTitle("当前文件：" + fileName);
        return true;
    }

    @Override
    public void onLocationChanged(Location location) {

        LatLng pos = new LatLng(location.getLatitude(), location.getLongitude());
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, aMap.getCameraPosition().zoom));
        aMap.addMarker(new MarkerOptions().position(pos).icon(BitmapDescriptorFactory.fromResource(R.drawable.gps_track)));
    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onSend(String track) {
        mockLocationThread.playNext();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mockLocationThread.shutDown();

        locationManager.removeUpdates(this);
        stopTestProvider();

        mMapView.onDestroy();

        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void stopTestProvider() {
        locationManager.clearTestProviderLocation(mocLocationProvider);
        locationManager.clearTestProviderStatus(mocLocationProvider);
        locationManager.clearTestProviderEnabled(mocLocationProvider);

        locationManager.setTestProviderEnabled(mocLocationProvider, false);
        locationManager.removeTestProvider(mocLocationProvider);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.start_btn:
                State state = mockLocationThread.getState();
                if (Thread.State.NEW == state) {
                    mockLocationThread.start(); // first start
                } else if (Thread.State.TERMINATED == state) {
                    mockLocationThread = null;
                    try {
                        mockLocationThread = new MockLocationThread(locationManager, HomeActivity.this, LocationManager.GPS_PROVIDER, trackData);
                        mockLocationThread.registerOnSendListener(HomeActivity.this);
                        mockLocationThread.start();
                        Toast.makeText(HomeActivity.this, "已开启", Toast.LENGTH_SHORT).show();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                aMap.clear(); // 清除先前的图层，不然会叠加很多位置信息
                break;
            case R.id.stop_btn:
                mockLocationThread.shutDown();
                break;
            case R.id.last_btn:
                mockLocationThread.playLast();
                break;
            case R.id.next_btn:
                mockLocationThread.interruptThread();
                break;
            case R.id.mapMode_btn:
                if (isSatellite) {
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);
                    isSatellite = false;
                } else {
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                    isSatellite = true;
                }
                break;
        }
    }
}